package com.pp.buvaka;

import com.pp.buvaka.table.Row;
import com.pp.buvaka.table.TableFormatException;

import java.io.*;
import java.util.ArrayList;


public class Files {
    /**
     * Check the 'in' folder for the .csv files
     * @param inputFolder - path to the 'in' folder
     * @throws java.io.FileNotFoundException
     * @return the array of .csv files inside the 'in' folder
     */
	public static File[] getTheListOfFiles(File inputFolder) throws FileNotFoundException{
        assert(inputFolder.isDirectory());

        ArrayList<File> result = new ArrayList<File>();

        if (!inputFolder.exists()){
            System.out.println("Can't found input dir.");
            throw new FileNotFoundException();
        }

        for (File fil : inputFolder.listFiles()){
            if (fil.getName().endsWith(".csv"))
                result.add(fil);
        }
        return result.toArray(new File[result.size()]);
	}

    /**
     * Parses and validates the input file. Check if the format of file is valid.
     * @param in - input file
     * @return the representation of valid file as ArrayList of String[] - to be simple converted into the Table
     * @throws TableFormatException when the file is not valid
     */
    public static ArrayList<String[]> parseAndValidateFile(File in) throws TableFormatException{

        ArrayList<String[]> result = new ArrayList<String[]>();

        BufferedReader br = null;
        try {
             br = new BufferedReader(new FileReader(in));

            String line;
            int columnsLength = -1;
            while ((line = br.readLine()) != null) {
                String[] elems = line.split(":", -1);
                columnsLength = (columnsLength == -1) ? elems.length : columnsLength;
                if (elems.length != columnsLength){
                    throw new TableFormatException("Your file is not valid! Size of each row have to be similar. The size of row \"" + line + "\" is different than in all previous rows ");
                } else if(elems.length > Row.MAX_SIZE) {
                    throw new TableFormatException("Max length is 26. Please cut the line \"" + line + "\"");
                }
                result.add(elems);
            }

        } catch (IOException e){
            e.printStackTrace();
        }
        finally{
            try {
                br.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        return result;
    }
}
